package com.yisen.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.hash.Jackson2HashMapper;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisTest {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    public void test(){
//        ValueOperations vo = stringRedisTemplate.opsForValue();
//        vo.set("hello","kinth");
        // 存储复杂类型hash
        /*
         * 对象转map用，boolean代表对象是否扁平化。
         *      false-> car       = {name:"法拉利"}
         *      true -> car::name = "法拉利"
         */
        Jackson2HashMapper jackson2HashMapper = new Jackson2HashMapper(objectMapper, false);
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        Car car = new Car("法拉利");
        Persion persion = new Persion("张三",18,car);
        Map<String, Object> map = jackson2HashMapper.toHash(persion);
        hashOperations.putAll("zhangsan",map);
        // 发布订阅 ooxx代表要发布订阅的主题名称。
        RedisConnection cc = stringRedisTemplate.getConnectionFactory().getConnection();
        cc.subscribe(new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                byte[] body = message.getBody();
                System.out.println(new String(body));
            }
        }, "ooxx".getBytes());

    }
}
